<template>
  <div>
    <!-- 筛选区域 -->
    <div class="card" style="margin-bottom: 15px; padding: 10px;">
      <div class="filter-group">
        <el-select
            v-model="data.selectedExam"
            placeholder="请选择考试"
            style="width: 180px;"
            clearable
        >
          <el-option
              v-for="exam in data.examOptions"
              :key="exam.examId"
              :label="exam.examName"
              :value="exam.examId"
          />
        </el-select>
        <span class="input-desc">选择要查看的考试</span>
      </div>
      <div class="filter-group">
        <el-input
            v-model="data.firstClassName"
            placeholder="请填写初始班级"
            style="width: 120px;"
        ></el-input>
        <span class="input-desc">初始班级</span>
      </div>
      <div class="filter-group">
        <el-input
            v-model="data.finallyClassName"
            placeholder="请填写结束班级"
            style="width: 120px;"
        ></el-input>
        <span class="input-desc">结束班级</span>
      </div>
      <div class="filter-group">
        <el-input
            v-model="data.specifiedScore"
            placeholder="指定分数"
            type="number"
            style="width: 80px;"
        ></el-input>
        <span class="input-desc">用于统计超过该分数的人数</span>
      </div>

      <div class="filter-group">
        <el-input
            v-model="data.excellentScore"
            placeholder="优秀分数线"
            type="number"
            style="width: 80px;"
        ></el-input>
        <span class="input-desc">优秀分数线</span>
      </div>

      <div class="filter-group">
        <el-input
            v-model="data.passScore"
            placeholder="及格分数线"
            type="number"
            style="width: 80px;"
        ></el-input>
        <span class="input-desc">及格分数线</span>
      </div>

      <div class="filter-actions">
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="info" @click="reset">重 置</el-button>
        <el-button type="info" style="background-color: #7e55fc;" @click="exportData">批量导出</el-button>
        <el-button type="text" @click="toggleColumnSettings">
          <el-icon>
            <Setting/>
          </el-icon>
          列设置
        </el-button>
      </div>
    </div>

    <!-- 列显示设置弹窗 -->
    <el-dialog
        style="margin-top: 10px"
        v-model="data.columnSettingVisible"
        title="表格列设置"
        width="400px"
        destroy-on-close
    >
      <el-checkbox-group v-model="data.visibleColumns">
        <el-checkbox
            v-for="column in allColumns"
            :key="column.prop"
            :label="column.prop"
            style="display: block; margin: 10px 0;"
        >
          {{ column.label }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="data.columnSettingVisible = false">取消</el-button>
        <el-button type="primary" @click="saveColumnSettings">确定</el-button>
      </template>
    </el-dialog>

    <!-- 表格区域 -->
    <div class="card" style="margin-bottom: 5px; width: 100%;">
      <el-table stripe max-height="500"
                :data="data.tableData" style="width: 100%"
                :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}"
      >
        <!-- 班级列 - 默认显示且不可隐藏 -->
        <!--        <el-table-column prop="className" fixed label="班级" sortable width="80">-->
        <!--          <template #default="scope">-->
        <!--            <div style="display: flex; align-items: center">-->
        <!--              <el-tag effect="dark">{{ scope.row.className }}</el-tag>-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="className" fixed label="班级" sortable width="80">
          <template #default="scope">
            <!-- Tooltip 组件：content 绑定对应教师，placement 控制弹窗位置 -->
            <el-tooltip
                :content="`数学：${data.classTeacherMap[scope.row.className] || '暂无信息'}`"
                placement="top"
                effect="dark"
                trigger="hover"
                :show-arrow="true"
            >
              <div style="display: flex; align-items: center; cursor: pointer;">
                <!-- 原有标签保持不变，添加鼠标指针样式 -->
                <el-tag effect="dark">{{ scope.row.className }}</el-tag>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 动态列 - 根据设置显示或隐藏 -->
        <el-table-column
            v-if="isColumnVisible('totalStudents')"
            prop="totalStudents"
            label="人数"
            sortable
            width="80"
        />
        <el-table-column
            v-if="isColumnVisible('rank')"
            prop="rank"
            label="排名"
            width="60"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-tag type="danger" effect="dark">{{ scope.$index + 1 }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            v-if="isColumnVisible('totalPoints')"
            prop="totalPoints"
            label="积分"
            sortable
            width="80"
        />
        <el-table-column
            v-if="isColumnVisible('averageScore')"
            prop="averageScore"
            label="平均分"
            sortable
            :formatter="formatAVGScore"
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('maxScore')"
            prop="maxScore"
            label="最高分"
            sortable
            :formatter="formatScore"
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('minScore')"
            prop="minScore"
            label="最低分"
            sortable
            :formatter="formatScore"
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('excellentCount')"
            prop="excellentCount"
            label="优秀数"
            sortable
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('excellentRate')"
            prop="excellentRate"
            label="优秀率"
            sortable
            :formatter="formatPercentage"
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('passCount')"
            prop="passCount"
            label="及格数"
            sortable
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('passRate')"
            prop="passRate"
            label="及格率"
            sortable
            :formatter="formatPercentage"
            width="100"
        />

        <el-table-column
            v-if="isColumnVisible('overSpecifiedScoreCount')"
            prop="overSpecifiedScoreCount"
            label="超指定分人数"
            sortable
            width="120"
        />

        <el-table-column
            v-if="isColumnVisible('segmentCounts')"
            label="分数段分布"
            width="120"
        >
          <template #default="scope">
            <el-button
                type="text"
                @click="showScoreDistribution(scope.row.segmentCounts, scope.row.totalStudents)"
                style="color: #409EFF"
            >
              查看分布
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
            v-if="isColumnVisible('actions')"
            label="分析"
            width="100px"
        >
          <template #default="scope">
            <el-button type="warning" icon="TrendCharts" circle @click="scoreAnalysis(scope.row)"></el-button>
          </template>
        </el-table-column>
        <!-- 动态分数段列 -->
        <!-- 动态分数段列（修改后） -->
        <el-table-column
            v-for="(segment, index) in sortedScoreSegments"
            :key="index"
            :label="segment.label"
            width="100"
        >
          <template #default="{ row }">
            {{ row.segmentCounts[segment.key] || 0 }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分数段分布弹窗 -->
    <!-- 分数段分布弹窗（修改后） -->
    <el-dialog
        v-model="data.distributionDialogVisible"
        title="分数段分布"
        width="600px"
        destroy-on-close
    >
      <div class="distribution-header" style="margin-bottom: 15px; font-weight: bold;">
        班级总人数: {{ data.totalStudents }}人
      </div>
      <div class="distribution-container">
        <!-- 遍历排序后的key列表 -->
        <div
            v-for="segment in sortedDistributionKeys"
            :key="segment"
            class="distribution-item"
        >
          <span class="segment-label">{{ segment }}分：</span>
          <span class="segment-count">
        {{ data.currentDistribution[segment].count }}人
        ({{ data.currentDistribution[segment].percentage }}%)
      </span>
          <div class="progress-bar">
            <el-progress
                :percentage="data.currentDistribution[segment].percentage"
                :stroke-width="8"
                :stroke-color="getProgressColor(segment)"
            ></el-progress>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.distributionDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 班级成绩变化图表弹窗 -->
    <el-dialog
        v-model="data.analysisDialogVisible"
        title="数据分析"
        width="800px"
        destroy-on-close
    >
      <!-- 加载状态 -->
      <el-loading v-if="data.chartLoading" target=".dialog-chart-container" text="数据加载中..."/>

      <!-- 图表容器 -->
      <div class="dialog-chart-container" style="width: 100%; height: 400px; position: relative;"></div>

      <!-- 无数据提示 -->
      <div v-if="!data.chartLoading && data.chartData.xAxis.length === 0" style="text-align: center; padding: 50px 0;">
        <el-empty description="暂无该班级的考试数据"></el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import * as echarts from "echarts";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import * as XLSX from "xlsx";
import {saveAs} from "file-saver";

// 定义所有可用列
const allColumns = [
  {prop: 'totalStudents', label: '人数'},
  {prop: 'averageScore', label: '平均分'},
  {prop: 'maxScore', label: '最高分'},
  {prop: 'minScore', label: '最低分'},
  {prop: 'excellentCount', label: '优秀人数'},
  {prop: 'excellentRate', label: '优秀率'},
  {prop: 'passCount', label: '及格人数'},
  {prop: 'passRate', label: '及格率'},
  {prop: 'overSpecifiedScoreCount', label: '超指定分人数'},
  {prop: 'totalPoints', label: '积分'},
  {prop: 'rank', label: '年级排名'},
  {prop: 'segmentCounts', label: '分数段分布'},
  {prop: 'actions', label: '分析'}
];

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  selectedExam: null,
  // 新增：班级-教师映射表
  classTeacherMap: {
    '701': '张文丽',
    '702': '付鑫豪',
    '703': '段文溪',
    '704': '张灿',
    '705': '常亚冬',
    '706': '周苗苗',
    '707': '王凡',
    '708': '杨友静',
    '709': '马金露',
    '710': '曲芳草',
    '711': '荆淼',
    '712': '郭鑫',
    '713': '万明杰',
    '714': '马一凡',
    '715': '朱雅婷',
    '716': '张莹莹',
    '717': '程硕',
    '718': '夏晨阳',
    '719': '姬玉净',
    '720': '杨芳',
    '721': '傅靖晗',
    '722': '赵瑞雪',
    '723': '禄浩然',
    '724': '吴卫娜',
    '725': '金朝阳',
    '726': '李欣欣',
    '727': '李雨',
    '728': '房慧',
    '729': '刘冰冰',
    '730': '李园园',
    '731': '李楠',
    '732': '周建业'
  },
  tableData: [],
  form: {},
  rows: [],
  examOptions: [],
  finallyClassName: '',
  firstClassName: '',
  specifiedScore: 0,
  excellentScore: 96,
  passScore: 72,
  distributionDialogVisible: false,
  columnSettingVisible: false,
  currentDistribution: {}, // 现在存储包含count和percentage的对象
  currentClass: null,
  totalStudents: 0, // 存储当前班级总人数，用于计算百分比
  // 默认显示所有列
  visibleColumns: loadColumnSettings(),
  analysisDialogVisible: false, // 图表弹窗显示状态
  chartLoading: false, // 图表数据加载状态
  chartData: { // 图表所需数据
    xAxis: [], // x轴：考试名称
    totalPoints: [], // 积分数据
    averageScores: [] // 平均分数据
  },
  currentClassName: '' // 当前操作的班级名称
});


// 生成动态列配置
// 排序后的分数段列配置
const sortedScoreSegments = computed(() => {
  if (data.tableData.length === 0) return [];
  // 获取第一个班级的分数段key（所有班级分数段结构一致）
  const allSegmentKeys = Object.keys(data.tableData[0].segmentCounts);
  // 排序key（高分到低分）
  const sortedKeys = sortSegmentKeys(allSegmentKeys);
  // 生成排序后的列配置
  return sortedKeys.map(key => ({
    key: key,
    label: formatSegmentLabel(key) // 复用原格式化函数
  }));
});

// 分数段标签格式化
const formatSegmentLabel = (key) => {
  return key
      .replace(/\[(\d+),(\d+)\)/, '$1-$2') // 处理区间格式
      .replace('120', '120');            // 处理最高分段
};

function loadColumnSettings() {
  try {
    const saved = localStorage.getItem('examStatsVisibleColumns');
    if (saved) {
      const parsed = JSON.parse(saved);
      // 验证保存的设置是否有效
      if (Array.isArray(parsed) && parsed.length > 0) {
        return parsed;
      }
    }
  } catch (e) {
    console.error('加载列设置失败:', e);
  }
  // 加载失败时返回默认设置
  return allColumns.map(col => col.prop);
}

// 检查列是否可见
const isColumnVisible = (prop) => {
  return data.visibleColumns.includes(prop);
};

// 切换列设置弹窗
const toggleColumnSettings = () => {
  data.columnSettingVisible = !data.columnSettingVisible;
};

// 保存列设置
const saveColumnSettings = () => {
  // 确保至少保留一个可见列
  if (data.visibleColumns.length === 0) {
    ElMessage.warning('至少要保留一列');
    return;
  }

  try {
    // 保存到localStorage
    localStorage.setItem(
        'examStatsVisibleColumns',
        JSON.stringify(data.visibleColumns)
    );
    ElMessage.success('列设置已保存');
  } catch (e) {
    console.error('保存列设置失败:', e);
    ElMessage.error('保存列设置失败');
  }

  data.columnSettingVisible = false;
};

onMounted(async () => {
  await fetchExams();
  if (data.examOptions.length > 0) {
    console.log('已初始化')
    load();
  }
});

const load = () => {
  if (!data.selectedExam) {
    ElMessage.error('请先选择考试!'); // 此时提示会正常显示
    return false;
  }
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  request.get('/fenxi/getAll', {
    params: {
      selectedExam: data.selectedExam,
      specifiedScore: data.specifiedScore,
      excellentScore: data.excellentScore,
      passScore: data.passScore,
      firstClassName: data.firstClassName,
      finallyClassName: data.finallyClassName,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data;
      console.log('加载数据:', res.data);
    } else {
      ElMessage.error(res.msg || '加载失败');
    }
  }).catch(err => {
    console.error('加载失败:', err);
    ElMessage.error('加载数据时发生错误');
  }).finally(() => {
    loading.close();
  });
};

const fetchExams = () => {
  return request.get('/exams/getExams').then(res => {
    if (res.code === '200') {
      data.examOptions = res.data
          .slice()
          .sort((a, b) => new Date(b.examTime) - new Date(a.examTime));

      if (data.examOptions.length > 0 && data.selectedExam === null) {
        data.selectedExam = data.examOptions[0].examId;
      }
    } else {
      ElMessage.error(res.msg || '加载考试列表失败');
    }
  });
};

const reset = () => {
  if (data.examOptions.length > 0) {
    data.selectedExam = data.examOptions[0].examId;
  } else {
    data.selectedExam = null;
  }
  data.specifiedScore = 0;
  data.excellentScore = 96;
  data.passScore = 72;
  data.firstClassName = '';  // 重置起始班级
  data.finallyClassName = '';    // 重置结束班级
  load();
};


const exportData = () => {
  console.log('导出函数触发'); // 验证是否进入函数
  if (!data.selectedExam) {
    ElMessage.warning('请先选择考试');
    return;
  }

  if (data.tableData.length === 0) {
    ElMessage.warning('没有可导出的数据');
    return;
  }

  // 1. 准备导出数据（过滤并格式化）
  const exportData = data.tableData.map(row => {
    // 处理可能为null的数值
    const safeToFixed = (value, decimalPlaces = 2) => {
      if (value === null || value === undefined || isNaN(value)) {
        return '0.00';
      }
      return Number(value).toFixed(decimalPlaces);
    };

    const formattedRow = {
      '班级': row.className || '',
      '人数': row.totalStudents || 0,
      '排名': row.rank || (data.tableData.indexOf(row) + 1),
      '积分': row.totalPoints || 0,
      '平均分': safeToFixed(row.averageScore),
      '最高分': safeToFixed(row.maxScore, 0),
      '最低分': safeToFixed(row.minScore, 0),
      '优秀数': row.excellentCount || 0,
      '优秀率': `${safeToFixed(row.excellentRate)}%`,
      '及格数': row.passCount || 0,
      '及格率': `${safeToFixed(row.passRate)}%`,
      '超指定分人数': row.overSpecifiedScoreCount || 0
    };

    // 2. 添加分数段数据（按排序后的顺序）
    sortedScoreSegments.value.forEach(segment => {
      const label = formatSegmentLabel(segment.key);
      formattedRow[`${label}分`] = row.segmentCounts[segment.key] || 0;
    });

    return formattedRow;
  });

  // 3. 创建工作簿和工作表
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '班级成绩统计');

  // 4. 调整列宽（自适应内容）
  const wscols = Object.keys(exportData[0]).map(key => ({
    wch: key.length > 10 ? 15 : key.length + 2
  }));
  worksheet['!cols'] = wscols;

  // 5. 导出文件
  const excelBuffer = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
  const blob = new Blob([excelBuffer], {type: 'application/octet-stream'});

  // 获取当前考试名称作为文件名
  const examName = data.examOptions.find(item => item.examId === data.selectedExam)?.examName || '考试成绩';
  saveAs(blob, `${examName}_班级统计_${new Date().toLocaleDateString()}.xlsx`);
  ElMessage.success('导出成功，正在下载···');
};


// 显示分数段分布 - 新增totalStudents参数
const showScoreDistribution = (distribution, totalStudents) => {
  data.totalStudents = totalStudents; // 保存班级总人数

  // 计算每个分数段占总人数的百分比
  const distributionWithPercentage = {};
  Object.keys(distribution).forEach(segment => {
    const count = distribution[segment];
    const percentage = totalStudents > 0 ? Math.round((count / totalStudents) * 100) : 0;
    distributionWithPercentage[segment] = {
      count,
      percentage
    };
  });

  data.currentDistribution = distributionWithPercentage;
  data.distributionDialogVisible = true;
};

// 根据分数段获取进度条颜色
const getProgressColor = (segment) => {
  if (segment === '120' || segment === '[114,120)' || segment === '[108,114)') {
    return '#409EFF'; // 高分段蓝色
  } else if (segment === '[102,108)' || segment === '[96,102)' || segment === '[84,96)') {
    return '#67C23A'; // 中高分段绿色
  } else if (segment === '[72,84)' || segment === '[60,72)') {
    return '#E6A23C'; // 及格分段黄色
  } else {
    return '#F56C6C'; // 低分段红色
  }
};

// 格式化平均分成绩显示
const formatAVGScore = (row, column, cellValue) => {
  if (cellValue === null || cellValue === undefined || cellValue === '') {
    return '无';
  }
  // 保留两位小数显示
  if (typeof cellValue === 'number') {
    return cellValue.toFixed(2);
  }
  return cellValue.toString();
};
//  格式化成绩显示
const formatScore = (row, column, cellValue) => {
  if (cellValue === null || cellValue === undefined || cellValue === '') {
    return '无';
  }
  // 保留两位小数显示
  // if (typeof cellValue === 'number') {
  //   return cellValue.toFixed(0);
  // }
  return cellValue.toString();
};

// 格式化百分比显示
const formatPercentage = (row, column, cellValue) => {
  if (cellValue === null || cellValue === undefined) {
    return '0.00%';
  }
  // 确保是数字并保留两位小数
  return `${parseFloat(cellValue.toString()).toFixed(2)}%`;
};

// 解析分数段的起始分数（用于排序）
const getSegmentStartScore = (segmentKey) => {
  if (segmentKey === '120') { // 单独处理满分段
    return 120;
  }
  // 匹配区间格式（如[114,120)），提取第一个数字作为起始分
  const match = segmentKey.match(/\[(\d+),/);
  if (match && match[1]) {
    return parseInt(match[1], 10);
  }
  return 0; // 异常情况默认最低
};

// 对分数段key进行排序（从高分到低分）
const sortSegmentKeys = (segmentKeys) => {
  // 复制原数组避免修改源数据
  return [...segmentKeys].sort((a, b) => {
    const scoreA = getSegmentStartScore(a);
    const scoreB = getSegmentStartScore(b);
    // 按起始分数降序排列（高分段在前）
    return scoreB - scoreA;
  });
};

// 排序后的分数段key（用于弹窗）
const sortedDistributionKeys = computed(() => {
  if (Object.keys(data.currentDistribution).length === 0) return [];
  return sortSegmentKeys(Object.keys(data.currentDistribution));
});
// 初始化图表
const initChart = () => {
  // 等待弹窗渲染完成（延迟100ms确保DOM存在）
  setTimeout(() => {
    const chartDom = document.querySelector('.dialog-chart-container');
    if (!chartDom) return;

    // 正确的ECharts初始化方式
    // 先销毁可能存在的旧实例
    const existingChart = echarts.getInstanceByDom(chartDom);
    if (existingChart) {
      echarts.dispose(existingChart);
    }

    // 创建新实例
    const myChart = echarts.init(chartDom);

    // 图表配置（双Y轴：左侧积分，右侧平均分）
    const option = {
      title: {
        text: `${data.currentClassName}班 积分/平均分变化趋势`,
        left: 'center',
        bottom: 350, // 标题底部距离图表底部的距离（增大此值让标题上移，远离图表）
        subtext: '点击可单独查看某项数据',
        subtextStyle: {fontSize: 12, color: '#666'},
        textStyle: {fontSize: 16}, // 主标题字号稍大，视觉上更清晰
        itemGap: 10 // 主标题与副标题之间的间距（默认10，可增大）
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {type: 'cross'}
      },
      legend: {
        data: ['积分', '平均分'],
        top: 60
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.chartData.xAxis,
        axisLabel: {
          rotate: 30, // 标签旋转避免重叠
          interval: 0 // 显示所有标签
        }
      },
      // 双Y轴配置
      yAxis: [
        {
          type: 'value',
          name: '积分',
          min: 0,
          axisLabel: {formatter: '{value}'}
        },
        {
          type: 'value',
          name: '平均分',
          min: 0,
          max: 120, // 假设满分150，可根据实际调整
          axisLabel: {formatter: '{value}'},
          position: 'right',
          offset: 0,
          // 右侧Y轴线条样式区分
          axisLine: {lineStyle: {color: '#67C23A'}},
        }
      ],
      series: [
        {
          name: '积分',
          type: 'line',
          data: data.chartData.totalPoints,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {width: 2},
          itemStyle: {color: '#409EFF'}
        },
        {
          name: '平均分',
          type: 'line',
          data: data.chartData.averageScores,
          symbol: 'square',
          symbolSize: 8,
          lineStyle: {width: 2},
          itemStyle: {color: '#67C23A'},
          yAxisIndex: 1 // 绑定右侧Y轴
        }
      ]
    };

    // 渲染图表
    myChart.setOption(option);

    // 监听窗口 resize 事件，自适应图表
    window.addEventListener('resize', () => myChart.resize());

    // 弹窗关闭时的清理函数
    const handleClose = () => {
      myChart.dispose();
      window.removeEventListener('resize', () => myChart.resize());
      data.analysisDialogVisible = false;
    };

    // 可以在这里给弹窗的关闭按钮绑定清理函数
  }, 100);
};
// 点击“操作”按钮触发：打开弹窗并加载数据
const scoreAnalysis = async (row) => {
  // 记录当前班级，打开弹窗
  data.currentClassName = row.className;
  data.analysisDialogVisible = true;
  data.chartLoading = true;
  // 清空历史数据
  data.chartData = {xAxis: [], totalPoints: [], averageScores: []};

  try {
    // 1. 获取所有考试（已按时间排序），避免重复请求
    const allExams = data.examOptions;
    if (allExams.length === 0) {
      ElMessage.warning('无考试数据');
      return;
    }

    // 2. 遍历所有考试，逐个查询该班级的数据
    // 用Promise.all并行请求（考试数量不多时高效）
    const examDataList = await Promise.all(
        allExams.map(exam => {
          // 调用现有接口，精准筛选当前班级（通过first/finallyClassName锁定）
          return request.get('/fenxi/getAll', {
            params: {
              selectedExam: exam.examId,
              // 关键：通过班级名称筛选，确保只返回当前班级数据
              firstClassName: data.currentClassName,
              finallyClassName: data.currentClassName,
              // 复用用户当前设置的分数参数（不影响班级数据筛选）
              specifiedScore: data.specifiedScore,
              excellentScore: data.excellentScore,
              passScore: data.passScore
            }
          }).then(res => {
            // 接口返回该考试中当前班级的数据（可能为空）
            return {
              examName: exam.examName, // 考试名称
              examTime: exam.examTime, // 考试时间（用于排序）
              // 提取该班级数据（res.data应为数组，取第一个元素）
              classData: res.code === '200' && res.data.length > 0 ? res.data[0] : null
            };
          });
        })
    );

    // 3. 整理数据（过滤无数据的考试，按时间排序）
    examDataList.forEach(item => {
      if (!item.classData) return; // 跳过无数据的考试
      // 填充x轴（考试名称）
      data.chartData.xAxis.push(item.examName);
      // 填充积分（无数据时补0）
      data.chartData.totalPoints.push(item.classData.totalPoints || 0);
      // 填充平均分（保留2位小数，无数据时补0）
      data.chartData.averageScores.push(
          item.classData.averageScore ? Number(item.classData.averageScore.toFixed(2)) : 0
      );
    });

    // 4. 绘制图表（弹窗打开后初始化ECharts）
    initChart();

  } catch (err) {
    console.error('加载数据失败:', err);
    ElMessage.error('加载趋势图数据失败');
  } finally {
    data.chartLoading = false;
  }
};
</script>

<style scoped>
.filter-group {
  display: inline-flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 10px;
}

.input-desc {
  margin-left: 8px;
  color: #666;
  font-size: 12px;
  max-width: 200px;
}

.filter-actions {
  display: inline-flex;
  align-items: center;
}

.filter-actions button {
  margin-right: 10px;
}

.distribution-container {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

.distribution-item {
  margin-bottom: 15px;
}

.segment-label {
  display: inline-block;
  width: 100px;
  font-weight: 500;
}

.segment-count {
  display: inline-block;
  width: 100px; /* 增加宽度以容纳百分比 */
}

.progress-bar {
  display: inline-block;
  width: calc(100% - 200px); /* 调整宽度以适应新的布局 */
  vertical-align: middle;
}

.card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
}
</style>
